if [ "$#" -ne 4 ]; then
    echo "Usage: $0 [mount|umount] <mount_point> <username:password> <webdav_url:port>"
    exit 1
fi


log_message() {
    echo "$(date): $1" >> "$LOG_FILE"
}

ACTION=$1
MOUNT_POINT=$2
CREDENTIALS=$3
URL_PORT=$4
IFS=':' read -r USERNAME PASSWORD <<< "${CREDENTIALS}"
IFS=':' read -r URL PORT <<< "${URL_PORT}"

SECRETS_FILE="$HOME/.davfs2/secrets"
mkdir -p "$(dirname "$SECRETS_FILE")"
echo "https://${URL}:${PORT} ${USERNAME} ${PASSWORD}" >> "$SECRETS_FILE"
chmod 600 "$SECRETS_FILE"

if [ "$ACTION" == "mount" ]; then
    # 创建挂载点目录（如果不存在）
    mkdir -p "${MOUNT_POINT}"
    
    # 检查网络连接
    if ! ping -c 1 -W 5 "${URL}" > /dev/null 2>&1; then
        log_message "Network to ${URL} is unreachable."
        echo "Failed to reach ${URL}. Please check your network connection."
        exit 1
    fi

    # 尝试挂载 WebDAV 网盘
    if ! mount -t davfs "https://${URL}:${PORT}" "${MOUNT_POINT}" -o rw,uid=$(id -u),gid=$(id -g) 2>> "$LOG_FILE"; then
        log_message "Failed to mount WebDAV at ${MOUNT_POINT}."
        echo "Failed to mount WebDAV. Check ${LOG_FILE} for details."
        exit 1
    fi

elif [ "$ACTION" == "umount" ]; then
    # 尝试卸载 WebDAV 网盘
    if ! umount "${MOUNT_POINT}" 2>> "$LOG_FILE"; then
        log_message "Failed to unmount WebDAV at ${MOUNT_POINT}."
        echo "Failed to unmount WebDAV. Check ${LOG_FILE} for details."
        exit 1
    fi
else
    log_message "Invalid action: $ACTION"
    echo "Invalid action: $ACTION"
    exit 1
fi

log_message "Operation $ACTION completed for WebDAV at $MOUNT_POINT"
echo "Operation $ACTION completed for WebDAV at $MOUNT_POINT"